<?php

namespace app\admin\controller\replace;

use app\admin\model\Admin;
use app\admin\model\AdminNotice;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;

/**
 * 代班主任工作
 *
 * @icon fa fa-circle-o
 */
class Guide extends Backend
{

    public $group;

    /**
     * Guide模型对象
     * @var \app\admin\model\ReplaceGuide
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\ReplaceGuide;

        // 查询当前用户权限
        $group = $this->admin_group;
        $this->assign('group',$group);
        $this->group = $group;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    // 数据处理
    function data_processing($list){
        foreach ($list as $row) {
            $times = $row->times?ids_unlocking($row->times):[date('Y-m-d',strtotime($row->select_time))];
            $html = '';
            foreach ($times as $v){
                $html .= '<p>'.$v.'</p>';
            }
            $row->times = $html;
            $first_trial_admin = Admin::where('id',$row->first_trial_admin_id)->field('nickname,signature')->find();
            $row->first_trial_admin_name = $first_trial_admin?$first_trial_admin['nickname']:'';
            $row->first_trial_admin_signature = $first_trial_admin?$first_trial_admin['signature']:'';

            $end_trial_admin = Admin::where('id',$row->end_trial_admin_id)->field('nickname,signature')->find();
            $row->end_trial_admin_name = $end_trial_admin?$end_trial_admin['nickname']:'';
            $row->end_trial_admin_signature = $end_trial_admin?$end_trial_admin['signature']:'';

            $row->check_auth = $this->group['check_auth'];
            $row->current_admin_id = session('admin.id');

            $row->end_trial_admin_name = Admin::where('id',$row->end_trial_admin_id)->value('nickname');
            $row->visible(['id','current_admin_id','times','substitute_admin_id','teacher','course','admin','select_time','num',
                'remarks','type','status','reject_reason','first_trial_reject_reason','first_trial_admin_name','first_trial_time',
                'end_trial_reject_reason','end_trial_time','end_trial_admin_name','create_time','first_trial_admin_signature','end_trial_admin_signature','check_auth'
                ,'public_leave']);
        }
        return $list;
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $group_info = $this->group;
            $list = $this->model
                ->with(['admin','teacher'])
                ->where(function($query) use ($group_info,$limit){
                    if(!in_array($group_info['id'],[1,6,8])){ // 判断是否是超管 不限制所有都能查看
                        $query->where('replace_guide.admin_id',session('admin.id'));
                    }

                    if($limit == 999999){
                        $query->where('replace_guide.status',5);
                    }
                })
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $list = $this->data_processing($list);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $validate = $this->validate($params, 'ClassHour.add');
                    if ($validate !== true) exception($validate);
                    if($params['substitute_admin_id'] == session('admin.id')){
                        exception('被代老师不能是自己');
                    }else if(!isset($params['times']) || !$params['times']){
                        exception('请添加代班时间');
                    }
                    $html = '';
                    foreach ($params['times'] as $v){
                        // 判断是否有冲突
                        $ct = Db::table('b_replace_guide h')
                            ->join('b_admin a','a.id = h.admin_id')
                            ->where('h.substitute_admin_id',$params['substitute_admin_id'])
                            ->where('h.times','like',"%,{$v},%")
                            ->whereIn('h.status',[0,1,2,3,5])
                            ->value('nickname');
                        if($ct){
                            $html .= $v.'('.$ct.'提交了相同数据)';
                        }
                    }
                    if($html){
                        exception($html);
                    }

                    $params['times'] = ids_handle($params['times']);
                    $params['type'] = 2;
                    $params['admin_id'] = $this->auth->id;
                    $result = $this->model->allowField(true)->save($params);
                    if(!$result)exception('添加失败');
                    Db::commit();
                } catch (\Throwable $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 提交审核
     */
    public function to_examine($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $type = $this->request->get('type',0);
                if($type == 1){
                    $res = $row->save(array('status'=>'1'));
                }else if($type == 2){
                    $res = $row->save(array('status'=>'0'));
                }else{
                    $res = $row->save(array('status'=>'2'));
                }
                if (!$res)exception('提交成功');
                Db::commit();
            }  catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }

        return $this->view->fetch();
    }



    // 被代课列表
    public function cover_index(){
        //当前是否为关联查询
        $this->relationSearch = true;

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $AuthGroupAccessInfo = AuthGroupAccess::where('uid',$this->auth->id)->find();
            if(empty($AuthGroupAccessInfo))$this->error('登录错误');
            $group_info = $this->group;

            $list = $this->model->with(['admin','teacher'])
                ->where(function($query) use ($group_info,$limit){
                    if(!in_array($group_info['id'],[1,6,8])){ // 判断是否是超管 不限制所有都能查看
                        $query->where('replace_guide.substitute_admin_id',session('admin.id'));
                    }

                    if($limit == 999999){
                        $query->where('replace_guide.status',5);
                    }
                })
                ->where('replace_guide.status','>',0)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $list = $this->data_processing($list);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function auditing_index(){
        //当前是否为关联查询
        $this->relationSearch = true;

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $AuthGroupAccessInfo = AuthGroupAccess::where('uid',$this->auth->id)->find();
            if(empty($AuthGroupAccessInfo))$this->error('登录错误');
            $group_info = $this->group;

            $list = $this->model->with(['admin','teacher'])
                ->where(function($query) use ($group_info,$limit){
                    if(!in_array($group_info['id'],[1,6,8])){
                        if($group_info['check_auth'] == 1){
                            $query->whereIn('replace_guide.status',[
                                2,3,4,5,6
                            ]);

                        }else if($group_info['check_auth'] == 2){
                            $query->whereIn('replace_guide.status',[
                                3,5,6
                            ]);
                        }else{
                            $query->where('replace_guide.admin_id',-1);
                        }
                    }
                    if(in_array($group_info['id'],[1,6,8])){ // 判断是否是超管 不限制所有都能查看

                    }else{
                    }

                    if($limit == 999999){
                        $query->where('replace_guide.status',5);
                    }
                })
                ->where('replace_guide.status','>',1)
                ->where($where)
                ->orderRaw('field(replace_guide.status,2,3,5,4,6)')
                ->paginate($limit);

            $list = $this->data_processing($list);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }




    /**
     * 通过
     */
    public function pass_through($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                if($this->group['check_auth'] == 1){ // 初审
                    if($row->status != 2){
                        $this->error('当前状态无法操作');
                    }
                    AdminNotice::create(array('admin_id'=>$row->admin_id,'status'=>'1','content'=>'您提交的课时审核已初审通过'));
                    $res = $row->save(array('status'=>'3','first_trial_admin_id'=>$this->auth->id,'first_trial_time'=>date('Y-m-d H:i:s')));
                }else if($this->group['check_auth'] == 2){ // 终审
                    if($row->status != 3){
                        $this->error('当前状态无法操作');
                    }
                    AdminNotice::create(array('admin_id'=>$row->admin_id,'status'=>'1','content'=>'您提交的课时审核已终审通过'));
                    $res = $row->save(array('status'=>'5','end_trial_admin_id'=>$this->auth->id,'end_trial_time'=>date('Y-m-d H:i:s')));
                }else{
                    $this->error('您没有审核权限');
                }

                if (!$res)exception('审核成功');
                Db::commit();
            }  catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }

        return $this->view->fetch();
    }

    /**
     * 驳回
     */
    public function reject($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    if($this->group['check_auth'] == 1){ // 初审
                        if($row->status != 2){
                            $this->error('当前状态无法操作');
                        }
                        AdminNotice::create(array('admin_id'=>$row->admin_id,'status'=>'1','content'=>'您提交的课时审核被初审驳回  驳回原因：'.$params['reason']));
                        $res = $row->save(array('status'=>'4','first_trial_admin_id'=>$this->auth->id,'first_trial_reject_reason'=>$params['reason'],'first_trial_time'=>date('Y-m-d H:i:s')));
                    }else if($this->group['check_auth'] == 2){ // 终审
                        if($row->status != 3 && $row->status != 5){
                            $this->error('当前状态无法操作');
                        }
                        AdminNotice::create(array('admin_id'=>$row->admin_id,'status'=>'1','content'=>'您提交的课时审核被终审驳回  驳回原因：'.$params['reason']));
                        $res = $row->save(array('status'=>'6','end_trial_admin_id'=>$this->auth->id,'end_trial_reject_reason'=>$params['reason'],'end_trial_time'=>date('Y-m-d H:i:s')));
                    }else{
                        $this->error('您没有审核权限');
                    }
                    if(!$res)exception('驳回失败');
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 批量审核
     */
    public function batch_examine()
    {
        Db::startTrans();
//        try {
        $idStr = $this->request->post('ids','');
        $type = $this->request->post('type','pass');
        $ids = json_decode($idStr,true);
        if(empty($ids))exception('请勾选您需操作的内容');
        if($this->group['check_auth'] == 0){
            exception('您没有审核权限');
        }
        $number = 0;
        if($type == 'pass'){
            foreach ($ids as $v){
                $info = $this->model->get($v);
                if (!$info){
                    exception('未找到ID:'.$v.'的内容');
                }

                if($this->group['check_auth'] == 1){ // 初审
                    $number++;
                    if($info['status'] != 2){
                        exception('ID:'.$v.'的状态不正确，请先移除');
                    }
                    AdminNotice::create(array('admin_id'=>$info->admin_id,'status'=>'1','content'=>'您提交的课时审核已初审通过'));
                    $res = $info->save(array('status'=>'3','first_trial_admin_id'=>$this->auth->id,'first_trial_time'=>date('Y-m-d H:i:s')));
                }else if($this->group['check_auth'] == 2){ // 终审
                    $number++;
                    if($info['status'] != 3){
                        $this->error('ID:'.$v.'的状态不正确，请先移除');
                    }
                    AdminNotice::create(array('admin_id'=>$info->admin_id,'status'=>'1','content'=>'您提交的课时审核已终审通过'));
                    $res = $info->save(array('status'=>'5','end_trial_admin_id'=>$this->auth->id,'end_trial_time'=>date('Y-m-d H:i:s')));
                }
                if (!$res)exception('ID:'.$v.'审核失败');
            }
        }else{
            foreach ($ids as $v) {
                $info = $this->model->get($v);
                if (!$info)exception('未找到ID:'.$v.'的内容');
                if ($info['status'] != 2){
                    exception('ID:'.$v.'的状态不正确，请先移除');
                }
                $reason = '提交信息不完整';

                if($this->group['check_auth'] == 1){ // 初审
                    $number++;
                    if($info['status'] != 2){
                        $this->error('ID:'.$v.'的状态不正确，请先移除');
                    }
                    AdminNotice::create(array('admin_id'=>$info->admin_id,'status'=>'1','content'=>'您提交的课时审核被初审驳回  驳回原因：'.$reason));
                    $res = $info->save(array('status'=>'4','first_trial_admin_id'=>$this->auth->id,'first_trial_reject_reason'=>$reason,'first_trial_time'=>date('Y-m-d H:i:s')));
                }else if($this->group['check_auth'] == 2){ // 终审
                    $number++;
                    if($info['status'] != 3){
                        $this->error('ID:'.$v.'的状态不正确，请先移除');
                    }
                    AdminNotice::create(array('admin_id'=>$info->admin_id,'status'=>'1','content'=>'您提交的课时审核被终审驳回  驳回原因：'.$reason));
                    $res = $info->save(array('status'=>'6','end_trial_admin_id'=>$this->auth->id,'end_trial_reject_reason'=>$reason,'end_trial_time'=>date('Y-m-d H:i:s')));
                }
                if (!$res) exception('ID:'.$v.'驳回失败');
            }
        }
        if(!$number){
            exception('无可操作项');
        }
        Db::commit();
//        } catch (\Exception $e) {
//            Db::rollback();
//            $this->error($e->getMessage());
//        }
        $this->success('操作成功');
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if(!in_array($v->status,[0,1,4,6])){

                        Db::rollback();
                        $this->error('当前状态无法删除');
                    }
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
